package com.csun.cmny.provider.controller.admin;

import com.csun.cmny.provider.model.dto.log.UploadAppLogFileDto;
import com.csun.cmny.provider.model.dto.log.UploadAppLogRecordDto;
import com.csun.cmny.provider.utils.AppLogUtils;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2020-05-19 14:43
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping(value = "/api")
@Api(value = "Web-ApiRestController", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class AppLogController {

    @Resource
    private AppLogUtils appLogUtils;

    /**
     * 单个log
     */
    @RequestMapping(value = "/uploadAppLogRecord", method = RequestMethod.POST)
    public Wrapper uploadAppLogRecord(UploadAppLogRecordDto uploadAppLogRecordDto) {

        appLogUtils.print(uploadAppLogRecordDto);

        return WrapMapper.ok();
    }

    /**
     * log文件
     */
    @RequestMapping(consumes = "multipart/form-data", value = "/uploadAppLogFile",
            method = RequestMethod.POST)
    public Wrapper uploadAppLogFile(HttpServletRequest request, UploadAppLogRecordDto uploadAppLogRecordDto) {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> fileList = multipartRequest.getFiles("file");
        if (fileList.isEmpty()) {
            return WrapMapper.error("文件不能为空");
        }

        byte[] buffer = null;
        String fileName = "";
        try {
            for (MultipartFile multipartFile : fileList) {
                fileName = multipartFile.getOriginalFilename();
                if (PublicUtil.isEmpty(fileName)) {
                    continue;
                }
                buffer = multipartFile.getBytes();
                uploadAppLogRecordDto.setMessage(new String(buffer));
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        appLogUtils.print(uploadAppLogRecordDto);

        return WrapMapper.ok();
    }

}
